package com.gong.gongcloudpicture1.manager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.gong.gongcloudpicture1.common.BaseResponse;
import com.gong.gongcloudpicture1.model.vo.picture.PictureVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 缓存管理工具
 */
@Component
public class CacheManager {


    private static StringRedisTemplate stringRedisTemplate;

    @Resource
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        CacheManager.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 本地缓存
     */
    private static final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024) //初始容量
            .maximumSize(10000L) //最大存储多少数据
            // 缓存 5 分钟移除
            .expireAfterWrite(5L, TimeUnit.MINUTES)
            .build();


    public static Object getValue(String key, Class<?> clazz) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //从本地缓存中查询
        String cachedValue = LOCAL_CACHE.getIfPresent(key);
        if (StringUtils.isNotBlank(cachedValue)) {
            //如果命中, 将结果转换成对象并返回
            return JSONUtil.toBean(cachedValue, clazz);
        }
        //如果没有命中, 查询redis是否命中
        cachedValue = opsForValue.get(key);
        if (StringUtils.isNotBlank(cachedValue)) {
            //命中, 更新本地缓存数据
            LOCAL_CACHE.put(key, cachedValue);
            //返回redis数据
            return JSONUtil.toBean(cachedValue, clazz);
        }
        return null;
    }


    public static void setValue(String key, String value, long expireTime, TimeUnit timeUnit) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //将数据转换成json字符串
        String jsonValue = JSONUtil.toJsonStr(value);
        //更新本地缓存数据
        LOCAL_CACHE.put(key, jsonValue);
        //更新redis数据
        opsForValue.set(key, jsonValue, expireTime, timeUnit);
    }

}
